﻿// ------------------------------------------------------------------------------------------------
//  <copyright file="Serialize.cs" company="Iveely">
//    Copyright (c) Iveely Liu.  All rights reserved.
//  </copyright>
//  
//  <Create Time>
//    12/03/2012 20:12 
//  </Create Time>
//  
//  <contact owner>
//    liufanping@iveely.com 
//  </contact owner>
//  -----------------------------------------------------------------------------------------------

#region

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using IveelySE.Common.Log;

#endregion

namespace IveelySE.Common
{
    /// <summary>
    ///   序列化
    /// </summary>
    public class Serialize
    {
        /// <summary>
        ///   序列化异步对象
        /// </summary>
        private static readonly object SyncSer = new object();

        /// <summary>
        ///   反序列化异步对象
        /// </summary>
        private static readonly object SysncUnser = new object();

        /// <summary>
        ///   将对象序列化
        /// </summary>
        /// <param name="obj"> </param>
        /// <param name="fileName"> </param>
        public static bool Serailzable(Object obj, string fileName)
        {
            lock (SyncSer)
            {
                bool isOK;
                //如果包含建立目录信息
                if (fileName.Contains("\\"))
                {
                    //创建目录
                    if (!Directory.Exists(fileName.Substring(0, fileName.LastIndexOf('\\'))))
                    {
                        Directory.CreateDirectory(fileName.Substring(0, fileName.LastIndexOf('\\')));
                    }
                }
                //如果文件存在
                //if (File.Exists(fileName))
                //{
                //则删除
                //  File.Delete(fileName);
                //}
                //文件流
                FileStream fs = null;
                try
                {
                    //文件流创建
                    fs = new FileStream(fileName, FileMode.OpenOrCreate);
                    //二进制对象
                    var bf = new BinaryFormatter();
                    //执行序列化
                    if (obj == null)
                    {
                        return false;
                    }
                    bf.Serialize(fs, obj);
                    isOK = true;
                }
                catch (Exception exception)
                {
                    Common.Log.Content.GetInstance().Write(exception, MessageType.Warning);
                    isOK = false;
                }
                finally
                {
                    //如果文件流依然打开
                    if (fs != null)
                    {
                        //则关闭
                        fs.Close();
                    }
                }
                return isOK;
            }
        }

        /// <summary>
        ///   反序列化对象
        /// </summary>
        /// <param name="fileName"> 文件 </param>
        /// <returns> 返回对象 </returns>
        public static Object UnSerailzable(string fileName)
        {
            lock (SysncUnser)
            {
                FileStream fs = null;
                try
                {
                    if (File.Exists(fileName))
                    {
                        //文件流
                        fs = new FileStream(fileName, FileMode.Open);
                        //fs.Seek(0, SeekOrigin.Begin);
                        //二进制对象
                        var bf = new BinaryFormatter();
                        //执行序列化
                        Object obj = bf.Deserialize(fs);
                        //关闭流，这个很重要
                        fs.Close();
                        //返回
                        return obj;
                    }
                }
                catch (Exception ex)
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                    Content.GetInstance().Write(ex.Message, MessageType.Error);
                }
                return null;
            }
        }

        /// <summary>
        ///   字节转换为对象
        /// </summary>
        /// <param name="bytes"> 字节数组 </param>
        /// <returns> 返回对象 </returns>
        public static Object Byte2Obj(byte[] bytes)
        {
            var rems = new MemoryStream(bytes);
            return new BinaryFormatter().Deserialize(rems);
        }

        ///<summary>
        ///  对象转换为字节数组
        ///</summary>
        ///<param name="obj"> 需要传输的对象 </param>
        ///<returns> 返回字节数组 </returns>
        public static byte[] Obj2Byte(object obj)
        {
            var memoryStream = new MemoryStream();
            new BinaryFormatter().Serialize(memoryStream, obj);
            return memoryStream.GetBuffer();
        }
    }
}